package com.example.bmanliku;

import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author : yjz
 * @date : 2021/1/10 12:04
 * @des :
 */
public class FileActivity extends AppCompatActivity {

    private List<FileModel> fileModelList = new ArrayList<>();
    private FileAdapter fileAdapter;
    private TextView mCurrentPathTv;
    private RecyclerView mFileRecyclerView;
    private Stack<String> currentPathStack = new Stack<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file);
        mCurrentPathTv = findViewById(R.id.current_path_tv);
        File rootDirectory = Environment.getDataDirectory();
        //Log.e("TAG", "" + rootDirectory.getAbsolutePath());
        mCurrentPathTv.setText(String.format("当前路径：%s", Environment.getExternalStorageDirectory().getAbsolutePath()));
        // 文件列表
        mFileRecyclerView = findViewById(R.id.recycler_view);
        mFileRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        mFileRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        fileAdapter = new FileAdapter(this, fileModelList);
        // 列表点击监听
        fileAdapter.setOnRecyclerViewItemClickListen(new BaseRecyclerAdapter.OnRecyclerViewItemClickListen() {
            @Override
            public void onItemClickListen(View view, int position) {
                // 获取到当前点击item的数据
                final FileModel fileModel = fileAdapter.getItem(position);

               // Log.e("TAG", "fileModel = " + fileModel.toString());

                // 判断加密的文件类型
                if (!fileModel.isDirectory() && !fileModel.getName().endsWith("txt")) {
                    showToast("请选择txt结尾的文件");
                    return;
                }

                // 点击的是文件夹，直接查找对应文件夹下的文件
                if (fileModel.isDirectory()) {
                    pathRecord(fileModel);
                    initFileLists(new File(fileModel.getPath()));
                } else {
                    String txtFile = FileUtils.readTxtFile(fileModel.getPath());
                   // Log.e("TAG","file = " + txtFile);
                }
            }
        });

        // 加载文件列表
        initFileLists(Environment.getExternalStorageDirectory());
    }

    /**
     * 记录当前点击的路径
     */
    private void pathRecord(FileModel fileModel)
    {
        mCurrentPathTv.setText(String.format("当前路径：%s", fileModel.getPath()));
        // 如果栈为空,当前显示的文件路径入栈
        if (currentPathStack.empty())
        {
            currentPathStack.push(Environment.getExternalStorageDirectory().getAbsolutePath());
        }
        // 栈顶元素和当前点击的路径不一致
        if (!currentPathStack.peek().equals(fileModel.getPath()))
        {
            // 当前点击的路径入栈
            currentPathStack.push(fileModel.getPath());
        }
    }

    /**
     * 获取对应文件夹下的文件列表
     *
     * @param rootDirectory 文件列表
     */
    private void initFileLists(File rootDirectory)
    {
        if (rootDirectory.isDirectory())
        {
            File[] files = rootDirectory.listFiles();
            fileModelList.clear();
            //Log.e("TAG","size = " + files.length);
            if (files != null && files.length != 0)
            {
                for (File file : files)
                {
                    fileModelList.add(new FileModel(file.getName(), file.getAbsolutePath(), file.isDirectory()));
                }
            }
            fileAdapter.addData(fileModelList);
            mFileRecyclerView.setAdapter(fileAdapter);
            fileAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 显示Toast
     *
     * @param message 需要显示的内容
     */
    private void showToast(String message)
    {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    /**
     * 返回键监听
     */
    @Override
    public void onBackPressed()
    {
        // 查看栈里面的数据是否为空,不为空则返回上一个路径
        if (!currentPathStack.empty())
        {
            String pop = currentPathStack.pop();
           // Log.e("TAG", "pop path = " + pop);
            mCurrentPathTv.setText(String.format("当前路径：%s", pop));
            initFileLists(new File(pop));
            return;
        }
        super.onBackPressed();
    }
}
